package com.gui;

import com.manage.*;
import com.virtual.Run;
import javax.swing.*;
import java.awt.*;

public class GroupManagementPanel extends JPanel {
    private Run systemManager;
    private JComboBox<ClassRoom> classSelector;
    private JList<Group> groupList;
    private JList<Student> memberList;
    private DefaultListModel<Group> groupListModel;
    private DefaultListModel<Student> memberListModel;
    
    public GroupManagementPanel(Run systemManager) {
        this.systemManager = systemManager;
        initializeUI();
        // 初始化后立即更新列表
        updateClassSelector();
        // 如果有班级，选择第一个班级并更新小组列表
        if (classSelector.getItemCount() > 0) {
            classSelector.setSelectedIndex(0);
            updateGroupList();
        }
    }
    
    private void initializeUI() {
        setLayout(new BorderLayout(10, 10));
        
        // 顶部面板：班级选择
        JPanel topPanel = new JPanel();
        classSelector = new JComboBox<>();
        topPanel.add(new JLabel("选择班级："));
        topPanel.add(classSelector);
        
        // 中间面板：小组列表和成员列表
        JPanel centerPanel = new JPanel(new GridLayout(1, 2, 10, 0));
        
        // 小组列表面板
        JPanel groupPanel = new JPanel(new BorderLayout());
        groupListModel = new DefaultListModel<>();
        groupList = new JList<>(groupListModel);
        groupPanel.add(new JLabel("小组列表"), BorderLayout.NORTH);
        groupPanel.add(new JScrollPane(groupList), BorderLayout.CENTER);
        
        // 成员列表面板
        JPanel memberPanel = new JPanel(new BorderLayout());
        memberListModel = new DefaultListModel<>();
        memberList = new JList<>(memberListModel);
        memberPanel.add(new JLabel("成员列表"), BorderLayout.NORTH);
        memberPanel.add(new JScrollPane(memberList), BorderLayout.CENTER);
        
        centerPanel.add(groupPanel);
        centerPanel.add(memberPanel);
        
        // 底部面板：按钮
        JPanel buttonPanel = new JPanel();
        JButton addGroupBtn = new JButton("新增小组");
        JButton editGroupBtn = new JButton("编辑小组");
        JButton deleteGroupBtn = new JButton("删除小组");
        JButton addMemberBtn = new JButton("添加成员");
        JButton removeMemberBtn = new JButton("移除成员");
        JButton setScoreBtn = new JButton("设置分数");
        
        buttonPanel.add(addGroupBtn);
        buttonPanel.add(editGroupBtn);
        buttonPanel.add(deleteGroupBtn);
        buttonPanel.add(addMemberBtn);
        buttonPanel.add(removeMemberBtn);
        buttonPanel.add(setScoreBtn);
        
        // 添加到主面板
        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加事件监听
        classSelector.addActionListener(e -> {
            updateGroupList();
            memberListModel.clear(); // 清空成员列表
        });
        groupList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                updateMemberList();
            }
        });
        addGroupBtn.addActionListener(e -> showAddGroupDialog());
        editGroupBtn.addActionListener(e -> editSelectedGroup());
        deleteGroupBtn.addActionListener(e -> deleteSelectedGroup());
        addMemberBtn.addActionListener(e -> showAddMemberDialog());
        removeMemberBtn.addActionListener(e -> removeSelectedMember());
        setScoreBtn.addActionListener(e -> showSetScoreDialog());
        
        // 设置列表选择模式
        groupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        memberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 在 initializeUI 方法中设置首选大小
        groupList.setPreferredSize(new Dimension(200, 300));
        memberList.setPreferredSize(new Dimension(200, 300));
    }
    
    private void updateClassSelector() {
        classSelector.removeAllItems();
        for (ClassRoom classRoom : systemManager.getClasses()) {
            classSelector.addItem(classRoom);
        }
    }
    
    private void updateGroupList() {
        groupListModel.clear();
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedClass != null) {
            for (Group group : selectedClass.getGroups()) {
                groupListModel.addElement(group);
            }
        }
    }
    
    private void updateMemberList() {
        memberListModel.clear();
        Group selectedGroup = groupList.getSelectedValue();
        if (selectedGroup != null) {
            for (Student student : selectedGroup.getMembers()) {
                memberListModel.addElement(student);
            }
        }
    }
    
    private void showAddGroupDialog() {
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedClass != null) {
            String groupName = JOptionPane.showInputDialog(this, "请输入小组名称：");
            if (groupName != null && !groupName.trim().isEmpty()) {
                Group newGroup = new Group(generateGroupId(), groupName);
                selectedClass.addGroup(newGroup);
                updateGroupList();
                // 选中新添加的小组
                groupList.setSelectedValue(newGroup, true);
            }
        } else {
            JOptionPane.showMessageDialog(this, 
                "请先选择一个班级！", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
        }
    }
    
    private void editSelectedGroup() {
        Group selectedGroup = groupList.getSelectedValue();
        if (selectedGroup != null) {
            String newName = JOptionPane.showInputDialog(this, 
                "请输入新的小组名称：", selectedGroup.getName());
            if (newName != null && !newName.trim().isEmpty()) {
                selectedGroup.setName(newName);
                updateGroupList();
            }
        }
    }
    
    private void deleteSelectedGroup() {
        Group selectedGroup = groupList.getSelectedValue();
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedGroup != null && selectedClass != null) {
            int confirm = JOptionPane.showConfirmDialog(this, 
                "确定要删除该小组吗？", "确认删除", 
                JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                selectedClass.removeGroup(selectedGroup);
                updateGroupList();
            }
        }
    }
    
    private void showAddMemberDialog() {
        Group selectedGroup = groupList.getSelectedValue();
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedGroup != null && selectedClass != null) {
            // 创建可选学生列表（排除已在组内的学生）
            DefaultListModel<Student> availableStudents = new DefaultListModel<>();
            for (Student student : selectedClass.getStudents()) {
                if (!selectedGroup.getMembers().contains(student)) {
                    availableStudents.addElement(student);
                }
            }
            
            JList<Student> studentList = new JList<>(availableStudents);
            JScrollPane scrollPane = new JScrollPane(studentList);
            
            int result = JOptionPane.showConfirmDialog(this, scrollPane, 
                "选择要添加的学生", JOptionPane.OK_CANCEL_OPTION);
                
            if (result == JOptionPane.OK_OPTION && studentList.getSelectedValue() != null) {
                selectedGroup.addMember(studentList.getSelectedValue());
                updateMemberList();
            }
        }
    }
    
    private void removeSelectedMember() {
        Group selectedGroup = groupList.getSelectedValue();
        Student selectedStudent = memberList.getSelectedValue();
        if (selectedGroup != null && selectedStudent != null) {
            int confirm = JOptionPane.showConfirmDialog(this, 
                "确定要将该学生从小组中移除吗？", "确认移除", 
                JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                selectedGroup.removeMember(selectedStudent);
                updateMemberList();
            }
        }
    }
    
    private void showSetScoreDialog() {
        Group selectedGroup = groupList.getSelectedValue();
        if (selectedGroup != null) {
            String scoreStr = JOptionPane.showInputDialog(this, 
                "请输入小组分数：", selectedGroup.getScore());
            if (scoreStr != null && !scoreStr.trim().isEmpty()) {
                try {
                    double score = Double.parseDouble(scoreStr);
                    selectedGroup.setScore(score);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, 
                        "请输入有效的数字！", "输入错误", 
                        JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
    
    private int generateGroupId() {
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        return selectedClass.getGroups().size() + 1;
    }
    
    @Override
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            // 每次面板变为可见时更新数据
            updateClassSelector();
            updateGroupList();
            memberListModel.clear();
        }
    }
} 